<?php
$loader->requireOnce('includes/Utils.class.php');
/**
 * The controller to manage information of medicine.
 *
 */
class C_Medicine extends Controller {
	
	function C_Medicine($template_mod = "general") {
		parent::Controller();
		$this->template_mod = $template_mod;
		$this->setLayout('admin');
	}
		
	const USAGE_LIST_BY_QUANTITY_TITLE = "usageListByQuantityTitle";

	/**
	 * Action to open the view for managing medicine.
	 */
	public function actionManagement() {
        return $this->view->render('medicine_management.html');
	}

	/**
	 * Create or edit the default usage of medicine.
	 *
	 */
	public function actionEditMedicineDefUsage() {
        $medDefUsageId = $_GET['service_id'];
        $medDefUsage = Celini::newORDO('MedicineDefaultUsage');
        // load the medicine default usage to edit
        if (isSet($medDefUsageId) && $medDefUsageId != "") {
        	$medDefUsage->setup($medDefUsageId);
        }
        $this->assign_by_ref("medDefUsage", $medDefUsage);

        return $this->view->render('edit_medicine_default_usage.html');
	}

	/**
	 * Save medicine default usage.
	 *
	 */
	public function actionSaveMedicineDefUsageAjax() {
		// validate on server: TODO
		// save medicine default usage
		
		$usageTitleLang = L10nHelper::changeField(L10nHelper::getLocale(),"usage_title");
		$usageUnitLang = L10nHelper::changeField(L10nHelper::getLocale(),"usage_unit");
		$quantityTitleLang = L10nHelper::changeField(L10nHelper::getLocale(),"quantity_title");
		$data = array (
            $usageTitleLang => $_POST['usage_title'],
            'usage_num' => $_POST['usage_num'],
            $usageUnitLang => $_POST['usage_unit'],
            'dosage' => $_POST['dosage'],
		    'time' => $_POST['time'],
		    'quantity_num' => $_POST['quantity_num'],
		    $quantityTitleLang => $_POST['quantity_title']
        );
        $medDefUsage = Celini::newORDO('MedicineDefaultUsage');
        $medDefUsageId = $_POST['med_def_usage_id'];
        if (isset($medDefUsageId) && $medDefUsageId != "") {
            $medDefUsage->setup($medDefUsageId);
        }
        $medDefUsage->populateArray($data);
        $medDefUsage->persist();

        return $medDefUsage->get_id();
	}

	/**
	 * List all medicine default usage.
	 *
	 */
	public function actionListMedicineDefUsage() {
	   	$medDefUsageList = Celini::newORDO('DefaultUsage')->listAll();
        
        $usageArr = Utils::getEnumArrayKey(EnumerationConstant::PHA_DM_DEFAULT_USAGE);
        $usageUnit = Utils::getEnumArrayKey(EnumerationConstant::PHA_IMSE_UNIT);
                        
        $result = array();
        foreach ($medDefUsageList as $usageItem) {
            // [Uong] ngay [2] lan
            $usageItem['usage_title'] = $usageArr[$usageItem['usage_title_enum']];
            $usageItem['usage_num'] = $usageItem['usage_num'];
            
            // Moi lan [1] [vien]
            $usageItem['dosage'] = $usageItem['dosage'];
            $usageItem['dosage_title'] = $usageUnit[$usageItem['dosage_title_enum']];
            
            // [5] ngay
            $usageItem['time'] = $usageItem['time'];
            
            // [10] [vien]
            $usageItem['quantity_num'] =$usageItem['quantity_num'];
            $usageItem['quantity_title'] = $usageUnit[$usageItem['quantity_title_enum']];
            
            $result[] = $usageItem;
        }
                        
        $this->assign('medDefUsageList', $result);
        return $this->view->render('medicine_def_usage_list.html');
	}

	function actionSaveMedicineUsageAjax() {
		$usageTitleLang = L10nHelper::changeField(L10nHelper::getLocale(),"usage_title");
		$usageUnitLang = L10nHelper::changeField(L10nHelper::getLocale(),"usage_unit");
		$quantityTitleLang = L10nHelper::changeField(L10nHelper::getLocale(),"quantity_title");

		$locales = L10nHelper::getSupportedLocales();
		$id = $_POST['hid_id'];
		$obj = Celini::newORDO('MedicineDefaultUsage');
		if ( $id != '' ) {
			$obj->setup($id);


		}
		$title = $obj->get($usageTitleLang);
		$usageUnit = $obj->get($usageUnitLang);
		$quantityTitle = $obj->get($quantityTitleLang);
		
		if (!isset($title)
			||  $title == 0) {
			$data = array();
	       	foreach ( $locales as $lo => $la ) {
	       			$lo = L10nHelper::changeField($lo, "usage_title");
	       			$data[$lo] = $_POST['usage_title'];
	       	}
			$obj->populateArray($data);
	    	$obj->persist();
		} else {
			$data = array($usageTitleLang => $_POST['usage_title']);
			$obj->populateArray($data);
			$obj->persist();
		}

		if (!isset($usageUnit)
			||  $usageUnit == 0) {
			$data = array();
	       	foreach ( $locales as $lo => $la ) {
	       			$lo = L10nHelper::changeField($lo, "usage_unit");
	       			$data[$lo] = $_POST['usage_unit'];
	       	}
			$obj->populateArray($data);
	    	$obj->persist();
		} else {
			$data = array($usageUnitLang => $_POST['usage_unit']);
			$obj->populateArray($data);
			$obj->persist();
		}
		
		if (!isset($quantityTitle)
			||  $quantityTitle == 0) {
			$data = array();
	       	foreach ( $locales as $lo => $la ) {
	       			$lo = L10nHelper::changeField($lo, "quantity_title");
	       			$data[$lo] = $_POST['quantity_title'];
	       	}
			
			$obj->populateArray($data);
	    	$obj->persist();
		} else {
			$data = array($quantityTitleLang => $_POST['quantity_title']);
			$obj->populateArray($data);
			$obj->persist();
		}
	    $data = array (
            'usage_num' => $_POST['usage_num'],
            'dosage' => $_POST['dosage'],
		    'time' => $_POST['time'],
		    'quantity_num' => $_POST['quantity_num']
        );

        $obj->populateArray($data);
        $obj->persist();

    	return $obj->get_id();

	}

	/**
	 * Create/Edit a specific medicine.
	 *
	 * @return The view to edit medicine
	 */
	public function actionEditMedicine($medicineId = 0) {
	    if (isset($_POST['medicine_id'])) {
	        $tmp = Utils::sanitizeText($_POST['medicine_id']);
	        $medicineId = ($tmp > 0) ? $tmp : 0;
	    }
				
        $drug = Celini::newORDO('DrugMaterial', $medicineId);
        
        $defaultUsageId = $drug->get('default_usage_id');
        $selectedUsage = Celini::newORDO('DefaultUsage', $defaultUsageId)->get('usage_title_enum');
        
        $oriNameList = Celini::newORDO('DrugOriginalName')->listAll();
        $defaultUsageList = Utils::getEnumArrayKey(EnumerationConstant::PHA_DM_DEFAULT_USAGE);
        $unitList = Utils::getEnumArrayKey(EnumerationConstant::PHA_IMSE_UNIT);
        
        // assgin parameters for the view
        $this->assign_by_ref("drug", $drug);
        $this->assign('unitList', $unitList);
        $this->assign('defaultUsageList', $defaultUsageList);
        $this->assign('selectedUsage', $selectedUsage);
        $this->assign('originalNameList', $oriNameList);

        return $this->view->render('edit_medicine.html');
	}

	/**
	 * Save medicine.
	 *
	 */
	public function actionSaveMedicineAjax($medicineId = 0) {
	    if (isset($_POST['medicine_id'])) {
	        $tmp = Utils::sanitizeText($_POST['medicine_id']);
	        $medicineId = ($tmp > 0) ? $tmp : 0;
	    }

	    // Check if there is an default_usage available
	    // based on usage_title_enum and dosage_title_enum
	    $defaultUsageId = Celini::newOrdo('DefaultUsage')->checkExist($_POST['enum_usage'], $_POST['enum_unit']);
	    
	    // If there is no default usage available
	    if ($defaultUsageId == -1) {
	        return -1;
	    }
	    
	    $drug = Celini::newORDO('DrugMaterial', $medicineId);
	    $data = array(
	    	'proprietary_name'      => Utils::sanitizeText($_POST['medicine_name']),
	        'drug_original_name_id'	=> $_POST['original_name_id'],
	        'enum_unit_import_sell'	=> $_POST['enum_unit'],
	        'default_usage_id'		=> $defaultUsageId
	    );
	    $drug->populateArray($data);
	    $drug->persist();
	    	    	    
        return $drug->get_id();
	}

    /**
     * Return the view for searching medicine by name.
     *
     */
    public function actionListMedicine() {
        return $this->view->render('medicine_list.html');
    }

    /**
     * List all medicine with name criteria.
     *
     */

    public function actionListMedicineAjax() {
        $medName = Utils::sanitizeText($_POST['medicine_name']);
        $medicines = Celini::newORDO("DrugMaterial")->getMedicineListByName($medName);

        if (empty($medicines)) {
            return "<tr><td colspan='6'>" . L10nHelper::_('There is no data'). "</td></tr>";
        }
        
        $arrEnumUsage = Utils::getEnumArrayKey(EnumerationConstant::PHA_DM_DEFAULT_USAGE);
        $arrEnumUnit = Utils::getEnumArrayKey(EnumerationConstant::PHA_IMSE_UNIT);
        
        $body = "";
        $count = 1;
        // build content of table
        foreach ($medicines as $item) {
        	$aRow = "";
        	$id = $item['drug_material_id'];
        	// build a row of table
        	$aRow .= "<tr id='$id'>";
        	$aRow .= "<td>$count</td>";
        	$aRow .= "<td id='medicine_name_$id'>" . $item['proprietary_name'] . "</td>";
        	$aRow .= "<td>".$item['drug_original_name']."&nbsp;</td>";

        	$unitText = '';
            if (isset($arrEnumUnit[$item['enum_unit_import_sell']])) {
                $unitText = $arrEnumUnit[$item['enum_unit_import_sell']];
            }
        	$aRow .= "<td>" . $unitText . "&nbsp;</td>";
        	
            $usageTitleEnumText = '';
            if (isset($arrEnumUsage[$item['usage_title_enum']])) {
                $usageTitleEnumText = $arrEnumUsage[$item['usage_title_enum']];
            }
        	$aRow .= "<td>" . $usageTitleEnumText . "&nbsp;</td>";

        	
        	$aRow .= "<td>" .
        	    "<input type='button' onclick='javascript:editMedicine($id);' value='" . L10nHelper::_('Edit') ."'>" .
        		"&nbsp;<input type='button' onclick='javascript:deleteMedicine($id);' value='" . L10nHelper::_('Delete') . "'" .
        	 "</td>";
        	$aRow .= "</tr>";

            $body .= $aRow;
            $count++;
        }
        return $body;
    }

    public function actionDeleteMedicine() {
        $medicineId = Utils::sanitizeText($_POST['medicineId']);
        Celini::newOrdo('DrugMaterial')->delete($medicineId);
    }
    
    /**
     * Get default usage, price coresponding to a given insurance type case of a medicine
     *
     * @param string $medicineName Name of the medicine
     * @param unknown_type $insuranceType Insurance type
     * @return false if no medicine existing
     *  or else, return an array of fields
     */
    public function getMedicineInfo($medicineName, $insuranceType='no'){
        $obj = Celini::newORDO('Medicine');
        $medicineInfo = $obj->checkforExistingMedicineName($medicineName);
        if ($medicineInfo == false) return false;
        if($insuranceType != 'no' && $medicineInfo['insurance_support']=='yes'){
                $medicineInfo['insurance_price']   =  $medicineInfo['price'];
        }
        else {
            $medicineInfo['insurance_price']   =   0;
        }
        if(is_null($medicineInfo['price'])){
        	$medicineInfo['unit_price'] =   0;
        }

        else {
        	$medicineInfo['unit_price'] =   $medicineInfo['price'];
        }
        $medicineInfo['quantity_num']   =   1;
        $medicineInfo['original_price']     =   $medicineInfo['quantity_num']* $medicineInfo['unit_price'];
        $medicineInfo['insurance_price']    =   $medicineInfo['quantity_num']* $medicineInfo['insurance_price'];
        // Fix 939: [Emer] Medicine/equipment: check insurance payment for a medicine
        if ($medicineInfo['insurance_price'] > $medicineInfo['original_price']) {
        	$medicineInfo['insurance_price'] = $medicineInfo['original_price'];
        }
        $medicineInfo['patient_price']      =   $medicineInfo['original_price'] - $medicineInfo['insurance_price'];
        return json_encode($medicineInfo);
    }
}
?>